<!-- //?模块说明 =>  合同签章模块 addToTab-->
<template>
  <div class="contract-signature-view">
    <div class="section-box">
      <!-- pdf文件预览列表 -->
      <aside class="signature-img">
        <div class="info">
          <h3 class="name">pdf列表</h3>
          <ul>
            <li
              class="base"
              :class="{ baseActive: index === currentIndex }"
              v-for="(item, index) in pdfUrlList"
              :key="item.id"
              @click="preview(index, item)"
            >
              {{ item.name }}
            </li>
          </ul>
        </div>
      </aside>
      <!-- 主体区域 -->
      <section class="main-layout" :class="{ 'is-first': isFirst }">
        <!-- 操作 -->
        <div class="operate-box">
          <div class="page-change">
            <el-button class="btn-outline-dark" @click="prevPage"
              >上一页</el-button
            >
            <el-input
              style="text-align: center"
              class="input-box"
              v-model.number="pageNum"
              :max="defaultNumPages"
              @change="cutover"
            />

            <span class="default-text">/{{ defaultNumPages }}</span>
            <el-button class="btn-outline-dark" @click="nextPage"
              >下一页</el-button
            >
          </div>
        </div>
        <!-- 画图 -->
        <div
          class="out-view"
          ref="canvasScroll"
          :class="{ 'is-show': isShowPdf }"
        >
          <template>
            <div
              class="canvas-layout"
              ref="canvasLayout"
              v-for="item in numPages"
              :key="item"
            >
              <!-- pdf部分 -->
              <canvas class="the-canvas" />
              <!-- 盖章部分 -->
              <canvas class="ele-canvas"></canvas>
            </div>
          </template>
        </div>
        <i class="loading" v-loading="!isShowPdf" />
      </section>
      <!-- 位置信息 -->
      <div class="position-info">
        <div>
          <!-- 拖拽 -->
          <draggable
            v-model="mainImagelist"
            :group="{ name: 'itext', pull: 'clone' }"
            :sort="false"
            @end="end"
          >
            <transition-group type="transition">
              <li
                v-for="item in mainImagelist"
                :key="item.img"
                class="item"
                style="text-align: center"
              >
                <img :src="item.img" width="100%;" height="100%" class="img" />
              </li>
            </transition-group>
          </draggable>
          <el-button type="primary" @click="sign">签章</el-button>
        </div>
        <div>
          <div>
            <span class="title">签名位置</span>
            <span class="title clearSign" @click="clearSignature"
              >清空签章</span
            >
          </div>
          <el-radio-group
            v-if="Array.from(this.signPages.values()).length"
            class="ml10 mt10"
            v-model="signLocation"
          >
            <el-radio
              v-for="(item, index) in Array.from(this.signPages.values())"
              :key="index"
              :label="item"
            >
              <span @click.stop="handleRadio(item, $event)">
                {{ `第${item}页` }}
                {{ `(${pageSignNum.get(item)}处)` }}
              </span>
              <!-- <i
                class="el-icon-delete"
                @click.stop="removeSignature(item, $event)"
              ></i> -->
            </el-radio>
          </el-radio-group>
        </div>

        <ul class="nav">
          <li class="item" v-for="(item, index) in coordinateList" :key="index">
            <!-- <span>{{ item.name }}</span> -->
            <span>{{ item.page }}</span>
            <span>{{ item.left }}</span>
            <span>{{ item.top }}</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
// 拖拽插件
import draggable from "vuedraggable";
// pdf插件
import { fabric } from "fabric";
import workerSrc from "pdfjs-dist/legacy/build/pdf.worker.entry";

import QRCode from "qrcodejs2";

export default {
  name: "MySignH5",
  components: { draggable },
  dicts: ["idiom"],
  props: {
    signatureForm: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      // pdf地址
      pdfUrl: "",
      // pdf列表
      pdfUrlList: [
        {
          id: 1,
          name: "show.pdf",
          url: "http://localhost:8080/show.pdf",
        },
        {
          id: 2,
          name: "promise.pdf",
          url: "http://localhost:8080/promise.pdf",
        },
      ],
      // 左侧选中下标
      currentIndex: 0,
      // 左侧签章列表
      mainImagelist: [
        { img: "http://localhost:8080/seal.png" },
        // { img: "http://localhost:8080/sign.png" },
      ],
      // 右侧坐标数据
      coordinateList: [
        // { name: '名称', page: '所在页面', left: 'x坐标', top: 'Y坐标' },
      ],
      // 总页数
      numPages: 1,
      defaultNumPages: 1,
      // 当前页
      pageNum: 1,
      // 缩放比例
      scale: 1,
      // pdf是否显示
      isFirst: true,
      isShowPdf: false,
      // pdf最外层的out-view
      outViewDom: null,
      // 各页pdf的canvas-layout
      canvasLayoutTopList: [],
      // 用来签章的canvas数组
      canvasEle: [],
      // 绘图区域的宽高
      whDatas: null,
      // pdf渲染的canvas数组
      canvas: [],
      // pdf渲染的canvas的ctx数组
      ctx: [],
      // pdf渲染的canvas的宽高
      pdfDoc: null,
      // 签名位置
      signLocation: 1,
      // 签章列表
      signPages: new Map(),
      // 所有签章列表
      allSignList: new Map(),
      // 当前预览文件id
      currentFileId: 1,
      // 当前签章图片的缩放比
      imgScale: {
        scaleX: 1,
        scaleY: 1,
      },
      // 签名图片
      signImg: "http://localhost:8080/seal.png",
      // 删除签章图片id
      deleteSignId: "",
      // pdf缩放系数
      pdfScale: 1,
      // pdf每页缩放数组
      pdfScaleList: [],
      // 每一页的签章个数
      pageSignNum: new Map(),
      // 最后点击删除的元素
      lastDeleted: "",
      // 是否滚动
      isMove: true,
    };
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.showQRCode();
      this.preview(0, this.pdfUrlList[0]);
    });
  },
  methods: {
    // pdf预览
    preview(index, item) {
      this.isShowPdf = false;
      this.isFirst = true;
      this.currentIndex = index;
      this.pdfUrl = item.url;
      this.currentFileId = item.id;
      this.clearSignature(false);
      this.pageNum = 1;
      this.canvasLayoutTopList = [];
      this.numPages = 0;
      this.canvas = [];
      this.ctx = [];
      this.canvasEle = [];
      // 拿到全部的canvas-layout
      const canvasLayoutDom = document.querySelectorAll(".canvas-layout");
      // 画布清空
      canvasLayoutDom.forEach((v) => v.remove(v));
      this.outViewDom && (this.outViewDom.scrollTop = 40);
      this.$nextTick(() => {
        if (this.allSignList.has(item.id)) {
          this.showpdf(this.pdfUrl).then(() => {
            setTimeout(() => {
              this.allSignList.get(item.id).forEach((v) => {
                this.signPages.set(v.page, v.page);
                this.$forceUpdate();
                console.log(v);
                this.addSeal({
                  sealUrl: v.sealUrl,
                  left: v.left,
                  top: v.top,
                  index: v.index,
                  pageNum: v.page - 1,
                });
              });
            }, 500);
          });

          this.$forceUpdate();
        } else {
          this.showpdf(this.pdfUrl); // 接口返回的应该还有盖章信息，不只是pdf
        }
      });
    },
    /**
     * pdf相关部分
     */
    // 解析pdf  pdfjsLib.getDocument
    async showpdf(pdfUrl) {
      let pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js");
      pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc;
      return await pdfjsLib
        .getDocument({
          url: pdfUrl,
          rangeChunkSize: 65536,
          disableAutoFetch: false,
        })
        .promise.then((pdfDoc_) => {
          this.pdfDoc = pdfDoc_;
          this.numPages = this.pdfDoc.numPages;
          this.defaultNumPages = this.pdfDoc.numPages;
          this.$nextTick(() => {
            this.canvas = document.querySelectorAll(".the-canvas");
            this.canvas.forEach((item) => {
              this.ctx.push(item.getContext("2d"));
            });
            // 循环渲染pdf
            for (let i = 1; i <= this.numPages; i++) {
              this.getScaleBox(pdfDoc_.getPage(i)).then((res) => {
                this.scale = res;
                this.renderPage(i).then(() => {
                  this.renderPdf({
                    width: this.canvas[i - 1].width,
                    height: this.canvas[i - 1].height,
                  });
                });
              });
            }
            setTimeout(() => {
              this.renderFabric();
              this.canvasEvents();
            }, 300);
          });
        });
    },
    //根据容器宽度和PDF宽度确定缩放比例
    async getScaleBox(pdfPage) {
      let scale = "";
      await pdfPage.then((res) => {
        const [x1, , x2] = res._pageInfo.view;
        const pageWidth = x2 - x1;
        scale = document.querySelector(".out-view").offsetWidth / pageWidth;
      });
      return scale;
    },
    // 设置pdf宽高，缩放比例，渲染pdf
    renderPage(num) {
      this.pdfScaleList = [];
      const that = this;
      let data = this.pdfDoc.getPage(num).then((page) => {
        let viewport = page.getViewport({ scale: this.scale }); // 设置视口大小
        this.canvas[num - 1].height = viewport.height;
        this.canvas[num - 1].width = viewport.width;
        // let devicePixelRatio = window.devicePixelRatio || 1;
        // console.log(window.devicePixelRatio);
        // let backingStoreRatio =
        //   this.ctx[num - 1].webkitBackingStorePixelRatio ||
        //   this.ctx[num - 1].mozBackingStorePixelRatio ||
        //   this.ctx[num - 1].msBackingStorePixelRatio ||
        //   this.ctx[num - 1].oBackingStorePixelRatio ||
        //   this.ctx[num - 1].backingStorePixelRatio ||
        //   1;
        // that.pixelRatio = devicePixelRatio / backingStoreRatio;
        // console.log(
        //   "devicePixelRatio:",
        //   devicePixelRatio,
        //   ",backingStoreRatio:",
        //   backingStoreRatio,
        //   ",pixelRatio:",
        //   that.pixelRatio
        // );
        // if (that.pixelRatio !== 1)
        //   that.transform = [that.pixelRatio, 0, 0, that.pixelRatio, 0, 0];
        // viewport = page.getViewport({ scale: this.scale });
        // console.log(that.pixelRatio);
        // this.canvas[num - 1].height = viewport.height * that.pixelRatio;
        // this.canvas[num - 1].width = viewport.width * that.pixelRatio;
        // this.canvas[num - 1].style.height = viewport.height + "px";
        // this.canvas[num - 1].style.width = viewport.width + "px";
        // Render PDF page into canvas context
        const renderContext = {
          canvasContext: this.ctx[num - 1],
          viewport: viewport,
          // transform: that.transform,
        };
        page.render(renderContext);
      });
      return data;
    },
    // 设置绘图区域宽高
    renderPdf(data) {
      this.whDatas = data;
    },
    // 生成绘图区域
    renderFabric() {
      // 1. 拿到全部的canvas-layout
      const canvasLayoutDom = document.querySelectorAll(".canvas-layout");
      // 2. 循环遍历
      canvasLayoutDom.forEach((item, index) => {
        this.whDatas.width = this.canvas[index].width;
        this.whDatas.height = this.canvas[index].height;

        this.canvasLayoutTopList.push({ obj: item, top: item.offsetTop });
        // 3. 设置宽高和居中
        item.style.margin = "0 auto 18px";
        item.style.boxShadow = "4px 4px 4px #e9e9e9";

        // 4. 拿到盖章canvas
        const canvasEle = item.querySelector(".ele-canvas");
        // 5. 拿到pdf的canvas
        const pCenter = item.querySelector(".the-canvas");
        // 6. 设置盖章canvas的宽高
        canvasEle.width = pCenter.clientWidth;
        canvasEle.height = this.whDatas.height;

        // 7. 创建fabric对象并存储
        this.canvasEle.push(
          new fabric.Canvas(canvasEle, {
            selectionColor: "transparent",
            selectionBorderColor: "transparent",
          })
        );
        // 8. 设置盖章canvas的样式
        const container = item.querySelector(".canvas-container");
        container.style.position = "absolute";
        container.style.left = "50%";
        container.style.transform = "translateX(-50%)";
        container.style.top = "0px";
        container.addEventListener("touchstart", (e) => {
          e.preventDefault();
          this.lastPosY = e.touches[0].pageY;
        });
        container.addEventListener("touchmove", (e) => {
          // console.log('触摸移动', e);
          e.preventDefault();
          let height = e.touches[0].pageY - this.lastPosY;
          this.scrollTopHeight = Number(height);
          if (this.isMove) {
            console.log(-this.scrollTopHeight + this.outViewDom.scrollTop);
            this.$refs.canvasScroll.scrollTo({
              top: -this.scrollTopHeight + this.outViewDom.scrollTop,
              behavior: "smooth",
            });
          }
        });
        container.addEventListener("touchend", (e) => {
          // console.log('触摸结束', this.scrollTopHeight);
        });
      });

      // 现形
      this.isFirst = false;
      this.isShowPdf = true;
      this.outViewDom = document.querySelector(".out-view");
      // 开启监听窗口滚动
      this.outViewScroll();
    },
    // 开启监听窗口滚动
    outViewScroll() {
      this.outViewDom.addEventListener("scroll", this.outViewRun);
    },
    // 关闭监听窗口滚动
    outViewScrollClose() {
      this.outViewDom.removeEventListener("scroll", this.outViewRun);
    },
    // 窗口滚动
    outViewRun() {
      const scrollTop = this.outViewDom.scrollTop + 100;
      // const scrollTop = this.outViewDom.scrollTop;
      const topList = this.canvasLayoutTopList.map((item) => item.top);
      // 增加一个最大值
      topList.push(Number.MAX_SAFE_INTEGER);
      for (let index = 0; index < topList.length; index++) {
        const element = topList[index];
        if (element <= scrollTop && scrollTop < topList[index + 1]) {
          this.pageNum = index + 1;
          break;
        }
      }
      this.signLocation = this.pageNum;
    },
    /**
     * 签章相关部分
     */
    // 签章拖拽边界处理，不能将图片拖拽到绘图区域外
    canvasEvents() {
      this.canvasEle.forEach((item) => {
        item.on("object:moving", (e) => {
          const obj = e.target;
          // if object is too big ignore
          if (
            obj.currentHeight > obj.canvas.height ||
            obj.currentWidth > obj.canvas.width
          ) {
            return;
          }
          obj.setCoords();
          // top-left  corner
          if (obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0) {
            obj.top = Math.max(obj.top, obj.top - obj.getBoundingRect().top);
            obj.left = Math.max(
              obj.left,
              obj.left - obj.getBoundingRect().left
            );
          }
          // bot-right corner
          if (
            obj.getBoundingRect().top + obj.getBoundingRect().height >
              obj.canvas.height ||
            obj.getBoundingRect().left + obj.getBoundingRect().width >
              obj.canvas.width
          ) {
            obj.top = Math.min(
              obj.top,
              obj.canvas.height -
                obj.getBoundingRect().height +
                obj.top -
                obj.getBoundingRect().top
            );
            obj.left = Math.min(
              obj.left,
              obj.canvas.width -
                obj.getBoundingRect().width +
                obj.left -
                obj.getBoundingRect().left
            );
          }
          const findIndex = this.coordinateList
            .slice(1)
            .findIndex((coord) => coord.cacheKey == obj.cacheKey);
          const keys = [
            "width",
            "height",
            "top",
            "left",
            "angle",
            "scaleX",
            "scaleY",
          ];
          keys.forEach((item) => {
            this.coordinateList[findIndex + 1][item] = Math.ceil(
              obj[item] / this.scale
            );
          });
        });
      });
    },
    // 拖拽结束
    end(e) {
      // 找到当前拖拽到哪一个canvas-layout上
      const currentCanvasLayout =
        e.originalEvent.target.parentElement.parentElement;
      const findIndex = this.canvasLayoutTopList.findIndex(
        (item) => item.obj == currentCanvasLayout
      );
      if (findIndex == -1) return false;
      // 取整
      const left =
        e.originalEvent.layerX < 0
          ? 0
          : Math.ceil(e.originalEvent.layerX / this.scale);
      const top =
        e.originalEvent.layerY < 0
          ? 0
          : Math.ceil(e.originalEvent.layerY / this.scale);
      this.addSeal({
        sealUrl: this.signImg,
        left,
        top,
        index: e.newDraggableIndex,
        pageNum: findIndex,
      });
      this.signLocation = this.pageNum;
      this.signPages.set(this.pageNum, this.pageNum);
      this.$forceUpdate();
    },

    // 添加公章
    addSeal({ sealUrl, left, top, index, pageNum }) {
      const delAllDom = () => {
        // 暴力删除所有.el-icon-close类名元素
        let doms = document.querySelectorAll(`.el-icon-close`);
        if (doms && doms.length > 0) {
          doms.forEach((v) => {
            v.remove(v);
          });
        }
      };
      const clearFun = (e, isDown = false) => {
        this.clearCanvas = e.target;
        if (e.target) {
          let { cacheKey, aCoords } = e.target;
          if (isDown) {
            // 0.删除所有创建元素
            delAllDom();
            // 1.找到对应画布父节点
            let canvasFather = this.$refs.canvasLayout[pageNum];
            //2.创建删除节点
            let clearDom = document.createElement("i");
            //3.给子节点添加类名
            clearDom.className = `el-icon-close`;
            // 4.增加自定义id
            clearDom.setAttribute("id", `${cacheKey}`);
            // 隐藏关闭图标
            clearDom.style = `visibility: hidden;`;
            // 向父元素添加子元素
            canvasFather.appendChild(clearDom);
            // 获取创建的元素
            this.lastDeleted = document.getElementById(`${cacheKey}`);
            //为子节点添加点击事件
            this.lastDeleted.addEventListener("click", (e) => {
              e.stopPropagation();
              this.$nextTick(() => {
                if (e.target) {
                  delAllDom();
                  this.removeSignature(e.target, canvasFather);
                }
              });
            });
            // 隐藏关闭按钮
          }
          let pointX = aCoords.tr.x + 10;
          let pointY = aCoords.tr.y - 20;
          this.lastDeleted.style = `
                  visibility: visible;
                  left: ${pointX}px;
                  top: ${pointY}px;
                  z-index: 100;
                  position: absolute;
                `;
        }
      };
      fabric.Image.fromURL(sealUrl, (oImg) => {
        oImg.set({
          // 距离左边的距离
          left: left,
          // 距离顶部的距离
          top: top,
          // 角度
          // angle: 10,
          // 缩放比例，需要乘以scale
          // scaleX: this.scale,
          // scaleY: this.scale,
          index,
          // 禁止缩放
          lockScalingX: false,
          lockScalingY: false,
          // 禁止旋转
          lockRotation: false,
          // width:100,
          // height:100,
          // 设置以左下角为原点
          // originX: 'left',
          // originY: 'bottom',
        });
        this.canvasEle[pageNum]
          .add(oImg)
          .on("object:scaling", (e) => {
            // 图形缩放时触发；
            const { scaleX, scaleY } = e.target;
            this.imgScale = { scaleX, scaleY };
            this.isMove = e.target ? false : true;
            clearFun(e);
            // 保存签章信息
            // this.saveSignature({ pageNum, index, sealUrl });
          })
          .on("mouse:down", (e) => {
            console.log("鼠标按下", e);
            clearFun(e);
          })
          .on("object:moving", (e) => {
            clearFun(e);
          })
          .on("object:modified", (e) => {
            clearFun(e);
          })
          .on("object:rotating", (e) => {
            clearFun(e);
          })
          .on("selection:cleared", (e) => {
            // 画布内取消选中后的事件
            console.log("画布内取消选中后的事件", e);
            if (e.deselected && e.deselected.length) {
              delAllDom();
            }
          })
          .on("selection:created", (e) => {
            e.e.stopPropagation();
            // 初次选中图形目标的事件
            clearFun({ target: e.selected[0] }, true);
            console.log("初次选中图形目标的事件", e);
          })
          .on("selection:updated", (e) => {
            // 变更选中图形目标的事件
            console.log("变更选中图形目标的事件", e);
            delAllDom();
            if (e.selected && e.selected.length) {
              clearFun({ target: e.selected[0] }, true);
            }
          });
        this.saveSignature({ pageNum, index, sealUrl });
      });
      // this.removeActive();
    },

    // 保存签章
    saveSignature({ pageNum, index, sealUrl }) {
      // 1. 拿到当前签章的信息
      let length = 0;
      let pageConfig = this.coordinateList.filter(
        (item) => item.page - 1 == pageNum
      );
      if (pageConfig) length = pageConfig.length;
      const currentSignInfo = this.canvasEle[pageNum].getObjects()[length];
      // 2. 拼接数据
      const keys = [
        "width",
        "height",
        "top",
        "left",
        "angle",
        "scaleX",
        "scaleY",
      ];
      const obj = {};
      keys.forEach((item) => {
        obj[item] = Math.ceil(currentSignInfo[item] / this.scale);
      });
      obj.cacheKey = currentSignInfo.cacheKey;
      obj.sealUrl = sealUrl;
      obj.index = index;
      // obj.name = `${this.mainImagelist[index].name}${this.coordinateList.length}`;
      obj.name = `${this.coordinateList.length}`;
      obj.page = pageNum + 1;
      obj.scaleX = this.imgScale.scaleX;
      obj.scaleY = this.imgScale.scaleY;
      obj.pdfScale = this.pdfScaleList[pageNum];
      obj.pdfWidth = currentSignInfo.canvas.width / this.pdfScaleList[pageNum];
      if (this.pdfScaleList[pageNum] > 1) {
        obj.pdfHeight =
          currentSignInfo.canvas.height / this.pdfScaleList[pageNum];
      } else {
        obj.pdfHeight =
          currentSignInfo.canvas.height / this.pdfScaleList[pageNum];
      }

      this.coordinateList.push(obj);

      this.allSignList.set(this.currentFileId, this.coordinateList);

      this.pageSignNum.set(
        this.pageNum,
        this.canvasEle[pageNum].getObjects().length
      );
      console.log(this.coordinateList);
      this.$forceUpdate();
    },

    /**
     * 操作相关部分
     */
    // 上一页
    prevPage() {
      if (this.pageNum <= 1) return;
      this.pageNum--;
      // 滚动到指定位置
      this.outViewDom.scrollTop =
        this.canvasLayoutTopList[this.pageNum - 1].top;
      this.signLocation = this.pageNum;
    },
    // 下一页
    nextPage() {
      if (this.pageNum >= this.numPages) return;
      this.pageNum++;
      // 滚动到指定位置
      this.outViewDom.scrollTop =
        this.canvasLayoutTopList[this.pageNum - 1].top;
      this.signLocation = this.pageNum;
    },
    // 切换页码
    cutover() {
      this.outViewScrollClose();
      if (this.pageNum < 1) {
        this.pageNum = 1;
      } else if (this.pageNum > this.numPages) {
        this.pageNum = this.numPages;
      }
      // 滚动到指定位置
      this.outViewDom.scrollTop =
        this.canvasLayoutTopList[this.pageNum - 1].top;
      setTimeout(() => {
        this.outViewScroll();
      }, 500);
      this.signLocation = this.pageNum;
    },
    // 删除所有的签章选中状态
    removeActive() {
      this.canvasEle.forEach((item) => {
        item.discardActiveObject().renderAll();
      });
    },
    // 删除签章
    removeSignature(item, e) {
      // 1. 判断是否有选中的签章
      const findItem = this.canvasEle.filter((item) => item.getActiveObject());

      // 2.删除选中的签章的信息
      this.coordinateList = this.coordinateList.filter(
        (item) =>
          !findItem.some((obj) => {
            return obj.getActiveObject().cacheKey === item.cacheKey;
          })
      );
      // 3.删除选中的签章
      findItem.forEach((v) => {
        v.remove(v.getActiveObject());
      });
      // 4.更新所有签章列表
      this.allSignList.set(this.currentFileId, this.coordinateList);

      // this.canvasEle[item - 1].clear();
      // this.coordinateList.splice(item - 1, 1);
      // this.signPages.delete(item);
      // this.$forceUpdate();
      // this.$message.success("删除成功");

      // e.stopPropagation();
      //       this.canvasEle.forEach((item) => {
      //   item.clear();
      // });
      // // 1. 判断是否有选中的签章
      // const findItem = this.canvasEle.filter((item) => {
      //   return item.getActiveObject();
      // });
      // // 2. 判断选中签章的个数
      // if (findItem.length == 0)
      //   return this.$message.error('请选择要删除的签章');
      // // 3. 判断选中签章的个数是否大于1
      // if (findItem.length > 1) {
      //   this.removeActive();
      //   return this.$message.error('只能选择删除一个签章,请重新选择');
      // }
      // // 4. 拿到选中的签章的cacheKey
      // const activeObj = findItem[0].getActiveObject();
      // const findIndex = this.coordinateList.findIndex(
      //   (item) => item.cacheKey == activeObj.cacheKey
      // );
      // // 5. 删除选中的签章
      // findItem[0].remove(activeObj);
      // // 6. 删除选中的签章的信息
      // this.coordinateList.splice(findIndex, 1);
      // return this.$message.success('删除成功');
    },
    // 清空签章
    clearSignature(flag = true) {
      this.canvasEle.forEach((item) => {
        item.clear();
      });
      this.coordinateList = [
        // { name: '名称', page: '所在页面', left: 'x坐标', top: 'Y坐标' },
      ];
      this.signPages.clear();
      if (flag) {
        this.allSignList.clear();
      }
      this.$forceUpdate();
    },
    // 构造传参结构
    transformObject(original) {
      const transformed = {};
      // 遍历原始对象的每个属性
      for (const key in original) {
        if (original.hasOwnProperty(key)) {
          const item = original[key];
          const pageNum = item.pageNum;

          // 如果转换后的对象中还没有对应页码的对象，则创建它
          if (!transformed[pageNum]) {
            transformed[pageNum] = {};
          }

          // 将当前项添加到对应页码的对象中，使用原始对象的键作为新对象的键
          // 同时，只复制需要的属性到新对象中
          const newItem = {
            ...item,
          };
          transformed[pageNum][key] = newItem;
        }
      }

      return transformed;
    },
    // 提交数据
    submitSignature() {
      let signPdfList = [];
      this.coordinateList = this.coordinateList.map((v) => {
        return {
          ...v,
          scaleX: this.canvasEle[v.page - 1]?.getActiveObject()?.scaleX || 1,
          scaleY: this.canvasEle[v.page - 1]?.getActiveObject()?.scaleY || 1,
        };
      });
      this.allSignList.set(this.currentFileId, this.coordinateList);
      let eleCanvas = document.querySelector(".ele-canvas");
      signPdfList = this.pdfUrlList
        .filter((v) => this.allSignList.has(v.id))
        .map((v) => {
          let obj = this.allSignList
            .get(v.id)
            .reduce((accumulator, currentValue) => {
              const {
                width,
                index,
                height,
                top,
                left,
                angle,
                scaleX,
                scaleY,
                sealUrl,
                pdfScale,
                pdfWidth,
                pdfHeight,
              } = currentValue;
              const newObj = {
                pageNum: currentValue.page,
                sealUrl,
                width,
                height,
                top,
                left,
                angle,
                scaleX,
                scaleY,
                index,
                leftx: "",
                topy: "",
                pdfScale,
                pdfWidth,
                pdfHeight,
              };
              // 使用currentValue的page属性作为新对象的键
              accumulator[currentValue.name] = newObj;
              return accumulator;
            }, {});
          return {
            bizId: this.signatureForm.bizId,
            id: this.signatureForm.id,
            // processInstanceId: this.signatureForm.processInstanceId,
            fileId: v.id,
            pdfHeight: eleCanvas.height,
            pdfWidth: eleCanvas.width,
            signs: JSON.stringify(this.transformObject(obj)),
          };
        });
    },

    // ====================================================右侧审批操作
    // 初始化签名
    sign() {
      this.addSeal({
        sealUrl: this.signImg,
        left: 0,
        top: 0,
        // index: this.coordinateList.length,
        index: 0,
        pageNum: this.pageNum - 1,
      });
      this.signLocation = this.pageNum;

      this.signPages.set(this.pageNum, this.pageNum);
      this.$forceUpdate();
    },
    // 二维码生成
    showQRCode() {
      if (this.$refs.qrcode2) {
        //先清除已有二维码
        this.$refs.qrcode2.innerHTML = "";
        new QRCode(
          this.$refs.qrcode2,
          {
            text: "www.baidu.com",
            width: 160,
            height: 160,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.Q,
          },
          (e) => {}
        );
      }
    },
    changeApproveType() {},
    //签名位置
    handleRadio(page, e) {
      e.stopPropagation();
      this.pageNum = page;
      this.cutover();
    },
  },
  destroyed() {},
};
</script>
<style lang="less" scoped>
.contract-signature-view {
  overflow: hidden;
  // height: 770px;
  /*pdf部分*/
  .ele-canvas {
    overflow: auto;
  }
  .title-operation {
    height: 80px;
    padding: 20px 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title {
      font-size: 20px;
      font-weight: 600;
    }
    border-bottom: 1px solid #e4e4e4;
  }
  .section-box {
    position: relative;
    display: flex;
    height: calc(100vh - 120px);

    .signature-img {
      width: 240px;
      min-width: 240px;
      background-color: #fff;
      padding: 40px 15px;

      border-right: 1px solid #e4e4e4;
      .info {
        margin-bottom: 38px;
        .name {
          font-size: 18px;
          font-weight: 600;
          color: #000000;
          line-height: 25px;
          margin-bottom: 20px;
        }
        .text {
          font-size: 14px;
          color: #000000;
          line-height: 20px;
        }
        .base {
          cursor: pointer;
        }
        .baseActive {
          color: blue;
        }
      }
      .item {
        padding: 10px;
        border: 1px dashed rgba(0, 0, 0, 0.3);
        &:not(:last-child) {
          margin-bottom: 10px;
        }
        .img {
          vertical-align: middle;
          width: 80px;
          height: 142px;
          background-repeat: no-repeat;
        }
      }
    }
    .main-layout {
      flex: 1;
      background-color: #f7f8fa;
      position: relative;

      &.is-first {
        .operate-box {
          opacity: 0;
        }
      }
      .operate-box {
        opacity: 1;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 40px;
        background-color: #fff;
        border-bottom: 1px solid #e4e4e4;
        display: flex;
        justify-content: center;
        align-items: center;
        .slider-box {
          width: 230px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-left: 1px solid #e4e4e4;
          border-right: 1px solid #e4e4e4;
          .slider {
            width: 120px;
          }
          .scale-value {
            margin-left: 24px;
            font-size: 16px;
            color: #000000;
            line-height: 22px;
          }
        }
        .page-change {
          display: flex;
          align-items: center;
          margin-left: 30px;
          .icon {
            cursor: pointer;
            padding: 0 5px;
            color: #c1c1c1;
          }
          .input-box {
            border: none;
            ::v-deep .el-input__inner {
              width: 34px;
              height: 20px;
              border: none;
              padding: 0;
              text-align: center;
              border-bottom: 1px solid #e4e4e4;
            }
          }
          .default-text {
            display: flex;
            line-height: 22px;
            margin-right: 5px;
            width: 110px;
          }
        }
      }
      .out-view {
        height: calc(100vh - 190px);
        margin: 40px auto;
        overflow-x: auto;
        overflow-y: auto;
        // padding-top: 20px;
        text-align: center;
        opacity: 0;
        transition: all 0.5s;
        &.is-show {
          opacity: 1;
          overflow: auto;
        }
        .canvas-layout {
          position: relative;
          text-align: center;
          margin: 0 auto 18px;
          // margin: 10px 10px 10px 10px;
          padding-top: 10px;
        }
      }
      .loading {
        width: 20px;
        height: 20px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 999;
        ::v-deep .el-loading-mask {
          background-color: transparent;
        }
      }
    }
    .position-info {
      width: 355px;
      min-width: 355px;
      border-left: 1px solid #e4e4e4;
      background-color: #fff;
      padding: 14px 15px;
      .title {
        font-size: 14px;
        font-weight: 400;
        color: #000000;
        line-height: 20px;
        padding-bottom: 18px;
      }
      .clearSign {
        margin-left: 10px;
        color: red;
        cursor: pointer;
      }
      .nav {
        display: flex;
        flex-direction: column;
        .item {
          display: flex;
          justify-content: space-between;
          padding: 10px 0;
          border-bottom: 1px solid #eee;
          &:first-child {
            background-color: #f7f8fa;
          }
          span {
            flex: 1;
            text-align: center;
            font-size: 12px;
            color: #000000;
            line-height: 20px;
          }
        }
      }
      .img {
        width: 150px;
        height: 80px;
      }
      .itemimg {
        width: 150px;
        height: 80px;
      }
      .btn-outline-dark:hover {
        color: #fff;
        background-color: #3e4b5b;
        border-color: #3e4b5b;
      }
    }
  }
}
</style>
